﻿using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;

namespace MichMan.Utilities.Requests
{
    public class WaitForMultipleRequest<T> : BaseRequestWithProgress, IRequest where T : IRequest
    {
        public WaitForMultipleRequest()
        {
        }

        private List<T> requests = new List<T>();

        public IEnumerable<T> Requests { get { return requests.AsEnumerable(); } }

        public void Add(T request)
        {
            requests.Add(request);
        }

        public bool Done { get { return CheckDone(); } }

        private bool CheckDone()
        {
            foreach (var req in requests)
            {
                if (!req.IsCompleted)
                {
                    return false;
                }
            }

            this.RequestStatus = Utilities.Requests.RequestStatus.Succeeded;
            return true;
        }

        public override void RunRequestAsync()
        {
            if (!CheckDone())
            {
                foreach (var req in requests)
                {
                    if (!req.IsCompleted)
                    {
                        req.RunRequestCompleted += new RunRequestCompletedEventHandler(req_RunRequestCompleted);
                        req.RunRequestAsync();
                    }
                }
            }
        }

        void req_RunRequestCompleted(object sender, RunRequestCompletedEventArgs e)
        {
            CheckDone();
        }
    }
}
